package club.jdiy.dev.dao.impl;

import club.jdiy.core.base.JDiyBaseDao;
import club.jdiy.core.ex.JDiyException;
import club.jdiy.dev.entity.JDiyUi;
import club.jdiy.dev.meta.ButtonMeta;
import club.jdiy.dev.meta.Lstr;
import club.jdiy.dev.meta.UiMeta;
import club.jdiy.dev.meta.ViewUiMeta;
import club.jdiy.dev.types.UiTpl;
import club.jdiy.utils.ArrayUtils;
import club.jdiy.utils.JsonUtils;
import club.jdiy.utils.StringUtils;

import java.util.*;

@SuppressWarnings("ALL")
public class JDiyUiDaoImpl extends JDiyBaseDao<JDiyUi, String> {

    public <T extends UiMeta> T getUiMeta(String id) {
        JDiyUi ui = findById(id).orElseThrow(() -> new JDiyException("获取界面配置信息失败(id={})", id));
        try {
            T uim = (T) JsonUtils.parse(ui.getMetaData(), ui.getType().metaClass);
            uim.setId(ui.getId());
            uim.setBindType(ui.getBindType());
            uim.setMainTable(ui.getMainTable());
            uim.setMainEntity(ui.getMainEntity());
            return uim;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new JDiyException("解析界面失败，请检查界面配置。" + ex.getMessage(), ex.getCause());
        }
    }

    public List<String> getRealms(String id) {
        UiMeta uiMeta = getUiMeta(id);
        if (uiMeta instanceof Lstr) {
            ArrayList<String> al =  __wrapRealms(
                    ((Lstr) uiMeta).getTopButtons(),
                    ((Lstr) uiMeta).getRowButtons()
            );

            //详情页内按钮权限：
            Arrays.stream(((Lstr) uiMeta).getRowButtons()).filter(btn -> btn.getGoPageType() == UiTpl.view).forEach(btn -> {
                al.addAll(__wrapRealms(((ViewUiMeta) getUiMeta(btn.getGoPageId())).getBtns()));
            });
            return al;
        } else if (uiMeta instanceof ViewUiMeta) {
            ButtonMeta[] btnMeta = ((ViewUiMeta) uiMeta).getBtns();
            ArrayList<String> al = __wrapRealms(btnMeta);
            return al;
        }
        return new ArrayList<>();
    }

    private ArrayList<String> __wrapRealms(ButtonMeta[]... btnMeta) {
        Map<String, Set<String>> rMap = new LinkedHashMap<>();
        if (btnMeta != null)
            for (ButtonMeta[] btns : btnMeta) {
                if (btns != null) {
                    Arrays.stream(btns).filter(btn -> StringUtils.hasText(btn.getGrantCode())).forEach(btn -> {
                        Set<String> ls = rMap.computeIfAbsent(btn.getGrantCode(), k -> new LinkedHashSet<>());
                        ls.add(btn.getText());
                    });
                }
            }
        ArrayList<String> al = new ArrayList<>();
        rMap.forEach((k, v) -> al.add(ArrayUtils.join(v, "/") + ":" + k));
        return al;
    }


}
